#include "feedmodel.h"
#include "downloader.h"
#include "feedrss.h"
#include "remotefilereader.h"

//Constructor with settings in argument
FeedModel::FeedModel(QSettings* settings):
    _settings(settings)
{
}

//Save the model
void FeedModel::save()
{

    QFile file(_settings->value("saveFileName","save.xml").toString());

    if(file.exists())
        file.remove();
    if(!file.open(QIODevice::WriteOnly))
        return;

    QDomDocument doc;
    QDomElement feed;
    QDomElement mp3;
    QStandardItem* item = NULL;
    QStandardItem* child = NULL;

    for( int feedNb = 0 ; ( (item = this->item(feedNb,0)) != NULL ) ; ++feedNb )
    {
        FeedItem* feedItem = dynamic_cast<FeedItem*>(item);
        feed = feedItem->toDomElt();

        for( int mp3Nb = 0 ; ( (child = item->child(mp3Nb,0)) != NULL ) ; ++mp3Nb )
        {
            Mp3Item* mp3Item = dynamic_cast<Mp3Item*>(item);
            mp3 = mp3Item->toDomElt();
            feed.appendChild(mp3);
        }
        doc.appendChild(feed);
    }

    file.write(doc.toByteArray());
    file.close();
}

//Restore the model
void FeedModel::restore()
{
    QFile file(_settings->value("saveFileName","save.xml").toString());

    if(!file.open(QIODevice::ReadOnly))
        return;

    QDomDocument doc;
    doc.setContent(file.readAll());

    QDomElement feed = doc.firstChildElement("Feed");
    QDomElement mp3;

    while( !feed.isNull() )
    {
        FeedItem* feedItem = new FeedItem(feed, _settings);

        mp3 = feed.firstChildElement("MP3");

        while( !mp3.isNull() )
        {
            Mp3Item* mp3Item = new Mp3Item(mp3, _settings);
            feedItem->appendRow(mp3Item);
            mp3 = mp3.nextSiblingElement("MP3");
        }

        this->invisibleRootItem()->appendRow(feedItem);

        feed = feed.nextSiblingElement("Feed");
    }

    file.close();
}

//SLOT - Add a new feed to the model
void FeedModel::addFeed(const QUrl& feedUrl)
{
    //Get the contents of the feed
    RemoteFileReader feedReader(feedUrl);
    FeedRSS rss(feedReader.getContents());

    //If not already created, create the item and add it to the model
    FeedItem* feedItem = findFeedItem(rss.getFeedName());
    if( feedItem == NULL )
    {
        feedItem = new FeedItem(rss, _settings);
        this->invisibleRootItem()->appendRow(feedItem);
    }

    //Update the feed
    feedItem->update();
}

//SLOT - Default processing of an item (when double clicked)
void FeedModel::defaultProcessItem(const QModelIndex& index)
{
    //Get the item
    BlogItem* item = dynamic_cast<BlogItem*>(itemFromIndex(index));
    
    //Call the item's default processing method
    item->defaultProcessing();
}

FeedItem* FeedModel::findFeedItem(const QString& feedName )
{
    return dynamic_cast<FeedItem*>(this->findItems(feedName).first());
}


